package ua.kpi.oblamskyiv.io;

import ua.kpi.oblamskyiv.LoginManager;
import ua.kpi.oblamskyiv.TestStats;
import ua.kpi.oblamskyiv.User;

import java.io.*;
import java.util.Scanner;

public class ClientIO {
    private static final InputStream IN = System.in;
    private static final OutputStream OUT = System.out;
    private static final File STATS_FILE = new File("stats.dat");

    public static final int AUTHORIZE = 1;
    public static final int TEST = 2;
    public static final int EXIT = 3;

    private Scanner scanner;
    private PrintStream printStream;

    public ClientIO() {
        scanner = new Scanner(IN);
        printStream = new PrintStream(OUT);
    }

    public void printMainMenu() {
        if (LoginManager.getInst().isLogged()) {
            printStream.println("1. Logout");
        } else {
            printStream.println("1. Login");
        }
        printStream.println("2. Make test");
        printStream.println("3. Exit");
    }

    public int getMenuChoice() {
        printStream.print("Enter choice: ");
        int choice = scanner.nextInt();

        printStream.println();
        return choice;
    }

    public String getUserName() {
        printStream.print("Enter name: ");
        String userName = scanner.nextLine();

        printStream.println();
        return userName;
    }

    /**
     * Writes user statistics into predefined file
     *
     * @param stats test statistics
     */
    public void writeStats(TestStats stats) {
        try {
            FileWriter fw = new FileWriter(STATS_FILE, true);
            PrintWriter printWriter = new PrintWriter(new BufferedWriter(fw));

            double usersScore = stats.getScore();
            User user = stats.getUser();

            printWriter.format("Name: %s; score: %.2f;\n",
                    user.getName(), usersScore);
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
